package com.xiaoming.mojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeRequest;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeResponse;
import com.xiaoming.mojcodesandbox.model.ExecuteMessage;
import com.xiaoming.mojcodesandbox.model.JudgeInfo;
import com.xiaoming.mojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;



import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Slf4j
public abstract class JavaCodeSandBoxTemplate implements CodeSandBox{


    private static final long TIME_OUT=5000L;
    private static final String GLOBAL_CODE_DIR_NAME="tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME="Main.java";
    ExecuteCodeResponse errExecuteCodeResponse;


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        //1把用户代码保存为文件
        File userCodeFile = saveCodeToFile(code);
        //2.编译代码 得到class文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(111);
        if(errExecuteCodeResponse != null &&errExecuteCodeResponse.getJudgeInfo()!=null && errExecuteCodeResponse.getMessage()!="")
        return errExecuteCodeResponse;
        System.out.println("编译信息"+compileFileExecuteMessage);

        // 3. 执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);
        if(errExecuteCodeResponse != null &&errExecuteCodeResponse.getJudgeInfo()!=null)
            return errExecuteCodeResponse;
        //4.收集输出结果
        ExecuteCodeResponse executeCodeResponse = getOutput(executeMessageList);
        //5.文件清理
        boolean b=deleteFile(userCodeFile);
        if(!b)
        {
            log.error("deleteFile error,userCodeFileLPath={}",userCodeFile);
        }
        return executeCodeResponse;

    }

    /**
     * 1把用户代码保存为文件
     * @param code
     * @return
     */
    public File saveCodeToFile(String code){
        //1把用户代码保存为文件
        //根目录
        String userDir=System.getProperty("user.dir");
        //代码包目录
        String globalCodePathName=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;

        if(!FileUtil.exist(globalCodePathName))
        {
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户代码隔离存放
        String  userCodeParentPath=globalCodePathName+File.separator+ UUID.randomUUID();
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_JAVA_CLASS_NAME;
        File file = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return file;
    }

    /**
     * 2.编译代码 得到class文件
     * @return
     */
    public ExecuteMessage compileFile(File file)
    {
        String compileCmd=String.format("javac -encoding utf-8 %s",file.getAbsoluteFile());
        try {
            Process process=Runtime.getRuntime().exec(compileCmd);
            String operationName="编译";
            ExecuteMessage executeMessage= ProcessUtils.runProcessAndGetMessage(process,operationName);
            errExecuteCodeResponse=new ExecuteCodeResponse();
            if(executeMessage.getExitValue()!=0)
            {
                JudgeInfo judgeInfo=new JudgeInfo();
                judgeInfo.setMessage("编译错误");
                judgeInfo.setTime(0L);
                errExecuteCodeResponse.setJudgeInfo(judgeInfo);
                //throw new RuntimeException("编译错误");
            }
            return executeMessage;
        }
        catch (Exception e) {
            
            throw new RuntimeException(e);
            
        }

    }

    /**
     * 3、执行文件，获得执行结果列表
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
//            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            try {
                Process runProcess=Runtime.getRuntime().exec(runCmd);
                //危险代码处理 限制运行时间不超过5s
                new Thread(()-> {
                    try {
                        Thread.sleep(TIME_OUT);
                        runProcess.destroy();
                        System.out.println("超时了，结束！");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start() ;

                String operationName="运行";
                ExecuteMessage executeMessage= ProcessUtils.runProcessAndGetMessage(runProcess,operationName);
                executeMessageList.add(executeMessage);
                System.out.println(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException("执行错误",e);
            }
        }
        return executeMessageList;
    }



    /**
     * 4、获取输出结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutput(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }

        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
            System.out.println(outputList);
        }
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setOutPutList(outputList);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        System.out.println("1111"+executeCodeResponse);
        return executeCodeResponse;
    }


/**
     * 删除文件
     * @param userCodeFile
     * @return*/



    public boolean deleteFile(File userCodeFile)
    {
        //5文件清理
        if(userCodeFile.getParent()!=null)
        {
            boolean del = FileUtil.del(userCodeFile);
            System.out.println("删除"+(del ? "成功" : "失败"));
            return del;
        }
        return true;


    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    public ExecuteCodeResponse getErrorResponse(Throwable e)
    {
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        executeCodeResponse.setOutPutList(new ArrayList<>());
        return executeCodeResponse;

    }

}
